<template>
  <div class="w-full">
    <div class="text-center mb-8">
      <h1 class="text-4xl md:text-5xl font-bold text-gray-800 mb-2">博客文章</h1>
      <p class="text-xl text-gray-600">分享技术知识和学习心得</p>
    </div>

    <!-- 筛选器 -->
    <div class="flex flex-col md:flex-row gap-4 mb-8">
      <div class="flex-1">
        <input v-model="searchQuery" type="text" placeholder="搜索文章..."
          class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:border-indigo-500 transition-colors duration-300">
      </div>
      <div class="md:w-48">
        <select v-model="selectedCategory"
          class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:border-indigo-500 transition-colors duration-300 bg-white cursor-pointer">
          <option value="">所有分类</option>
          <option value="技术">技术</option>
          <option value="前端">前端</option>
          <option value="JavaScript">JavaScript</option>
          <option value="Vue.js">Vue.js</option>
          <option value="CSS">CSS</option>
        </select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="pending" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-500"></div>
      <span class="ml-3 text-gray-600">加载中...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="text-center py-12">
      <div class="text-red-500 text-xl mb-4">加载失败</div>
      <button @click="refresh" class="px-4 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600">
        重新加载
      </button>
    </div>

    <!-- 文章列表 -->
    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
      <article v-for="article in articles" :key="article.id"
        class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 hover:-translate-y-1">
        <NuxtLink :to="`/blog/${article.slug}`" class="block h-48 overflow-hidden">
          <img :src="article.image" :alt="article.title"
            class="w-full h-full object-cover transition-transform duration-300 hover:scale-105">
        </NuxtLink>
        <div class="p-6">
          <div class="flex justify-between items-center mb-3 text-sm">
            <span class="text-indigo-500 font-medium">{{ article.category }}</span>
            <span class="text-gray-500">{{ article.date }}</span>
          </div>
          <NuxtLink :to="`/blog/${article.slug}`" class="block">
            <h2
              class="text-xl font-semibold text-gray-800 mb-3 line-clamp-2 hover:text-indigo-600 transition-colors duration-300">
              {{ article.title }}</h2>
          </NuxtLink>
          <p class="text-gray-600 mb-4 line-clamp-3">{{ article.excerpt }}</p>
          <div class="flex flex-wrap gap-2 mb-4">
            <span v-for="tag in article.tags" :key="tag"
              class="bg-gray-100 text-indigo-500 px-2 py-1 rounded-lg text-xs">
              {{ tag }}
            </span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-500 text-sm">{{ article.readTime }} 分钟阅读</span>
            <NuxtLink :to="`/blog/${article.slug}`"
              class="text-indigo-500 font-medium hover:text-indigo-600 transition-colors duration-300">
              阅读全文 →
            </NuxtLink>
          </div>
        </div>
      </article>
    </div>

    <!-- 分页 -->
    <div class="flex flex-col md:flex-row justify-center items-center gap-4">
      <button
        class="px-6 py-2 border-2 border-indigo-500 bg-white text-indigo-500 rounded-lg cursor-pointer transition-all duration-300 hover:bg-indigo-500 hover:text-white disabled:border-gray-300 disabled:text-gray-300 disabled:cursor-not-allowed disabled:hover:bg-white"
        :disabled="currentPage === 1">
        上一页
      </button>
      <span class="text-gray-600 text-sm">第 {{ currentPage }} 页，共 {{ totalPages }} 页 (共 {{ total }} 篇文章)</span>
      <button
        class="px-6 py-2 border-2 border-indigo-500 bg-white text-indigo-500 rounded-lg cursor-pointer transition-all duration-300 hover:bg-indigo-500 hover:text-white disabled:border-gray-300 disabled:text-gray-300 disabled:cursor-not-allowed disabled:hover:bg-white"
        :disabled="currentPage === totalPages">
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
// 获取路由参数
const route = useRoute()
const router = useRouter()

// 搜索和筛选状态
const searchQuery = ref(route.query.search || '')
const selectedCategory = ref(route.query.category || '')
const selectedTag = ref(route.query.tag || '')
const currentPage = ref(parseInt(route.query.page) || 1)
const itemsPerPage = 6

// 从后端获取文章数据
const { data: postsData, pending, error, refresh } = await useFetch('/api/posts', {
  query: computed(() => ({
    page: currentPage.value,
    limit: itemsPerPage,
    search: searchQuery.value || undefined,
    category: selectedCategory.value || undefined,
    tag: selectedTag.value || undefined
  }))
})

// 计算属性
const articles = computed(() => postsData.value?.posts || [])
const totalPages = computed(() => postsData.value?.totalPages || 1)
const total = computed(() => postsData.value?.total || 0)

// 分页方法
const goToPage = (page) => {
  currentPage.value = page
  updateQuery()
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    updateQuery()
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    updateQuery()
  }
}

// 更新 URL 查询参数
const updateQuery = () => {
  const query = {}
  if (searchQuery.value) query.search = searchQuery.value
  if (selectedCategory.value) query.category = selectedCategory.value
  if (selectedTag.value) query.tag = selectedTag.value
  if (currentPage.value > 1) query.page = currentPage.value.toString()

  router.push({ query })
}

// 监听筛选变化
watch([searchQuery, selectedCategory, selectedTag], () => {
  currentPage.value = 1
  updateQuery()
})

// 监听路由变化
watch(() => route.query, (newQuery) => {
  searchQuery.value = newQuery.search || ''
  selectedCategory.value = newQuery.category || ''
  selectedTag.value = newQuery.tag || ''
  currentPage.value = parseInt(newQuery.page) || 1
}, { immediate: true })
</script>